﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Snake.Core;
using Snake.Mapping;
using Snake.ORM.Reflection;
using Snake.SQL;
using Snake.SQL.SQLNode;

namespace Snake.ORM.SQLBuilder.SQLNode
{
    public class Update<T> : DbOperate
    {
         private T entity;

        public Update(DbContext context,T entity)
            : this(context.GetEntityMap(context.EntityType), context.NextAlias())
        {
            this.entity = entity;
        }

        public Update(EntityMap entityMap, BracketedName alias)
        {
            this.EntityMap = entityMap;
            this.Alias = alias;
        }

        public override void Render(SQLWriter writer)
        {
            writer.Append(SQLStrings.Update);
            writer.Append(EntityMap.Table);
            writer.AppendLine(SQLStrings.Set);
            List<PropertyMap> maps = EntityMap.Properties.Where(t => t.Column.Value != EntityMap.Key.Column.Value).ToList();
            for (var i = 0; i < maps.Count(); i++)
            {
                if (i > 0)
                    writer.Append(",");

                writer.AppendLine(EntityMap.Table + maps[i].Column);
                //拿属性的get方法的委托
                var getHandler = DynamicMethodCompiler.CreatePropertyGetHandler<T>(maps[i].Property);
                writer.Append("=");
                writer.Append("'"+getHandler(entity)+"'");
            }
            writer.AppendLine(SQLStrings.Where);
            writer.Append(EntityMap.Table+EntityMap.Key.Column.Value);
            writer.Append("=");
            var geth = DynamicMethodCompiler.CreatePropertyGetHandler<T>(EntityMap.Key.Property);
            writer.Append("'"+geth(entity)+"'");

        }

        public override bool VisitPath(DbContext context, PropertyInfo[] path, out BracketedName alias, out PropertyMap map)
        {
            throw new NotImplementedException();
        }

       
    }
}
